import os

from django.db.models import Q, F
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.template.loader import get_template
from django.urls import reverse
from django.views.generic.base import View
from rest_framework.generics import DestroyAPIView, GenericAPIView
from rest_framework.mixins import RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, CreateModelMixin, \
    ListModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from django.shortcuts import redirect

import re
import urllib.parse
import time

from myWebLibrary import settings

from apps.UploadFile.serializers import *
from apps.UploadFile.models import *

# 调用自己写的方法，用于将前端上传的音频写入本地文件夹中
from MyTool.WriteFiles import WriteFilesClass
from MyTool.DeleteMessage import DeleteMessageClass


# 定义全局context
globals_context = {
    "url":settings.URL
}

# 界面展示
class Show_html(View):
    # 主页
    def index_show(request):
        return render(request, 'index.html', context=globals_context)
    # 文本
    def text_show(request):
        return render(request, 'text_upload.html', context=globals_context)
    # 图片
    def img_show(request):
        return render(request,'imgs_upload.html',context=globals_context)
    # 音频
    def music_show(request):
        return render(request,'music_upload.html',context=globals_context)
    # 视频
    def video_show(request):
        return render(request,'video_upload.html',context=globals_context)
    # 个人中心
    def personalCenter_show(request):
        return render(request,'PersonalCenter.html',context=globals_context)
    # 关于我们
    def about_me_show(request):
        return render(request,'about_me.html',context=globals_context)
    # 上传成功
    def upload_successful(request):
        return render(request, 'upload_successful.html', context=globals_context)



# 上传文件

# 主页
class Index(View):
    def post(self,request):
        pass

# 文本上传
class Text_Upload(APIView):
    def post(self,request):
        # data = request.body.decode('utf-8')
        data = request.POST.get("text_upload")
        # # 去掉多余的加号
        # if "+" in data:
        #     data = data.replace("+", "")
        print(data)

        # 提取用户输入的文本信息
        # re_data = re.findall('text_upload=(.*?)&submit=%E6%8F%90%E4%BA%A4', data)

        # # 将url编码转换成中文
        # zh_data = [urllib.parse.unquote(i) for i in re_data][0]
        # print(f"将url编码转换成中文:{zh_data}")

        now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        print(f"当前时间:{now_time}")

        # 获取到用户的ip地址
        from MyTool.GeTIp import MyIp
        my_ip = MyIp()
        ip = my_ip.get_ip()
        print(f"ip:{ip}")



        # data_dict = {"username":"小红","time":now_time,"information":zh_data}
        data_dict = {"username":"小红","time":now_time,"information":data,"ip":ip}


        # 将用户上传的文本存入数据库中
        serializers = Text_UploadSerializers(data=data_dict)
        serializers.is_valid(raise_exception=True)
        serializers.save()


        context = {
            'url': globals_context.get('url'),
            # "data": zh_data,
            "data": data,
        }
        return render(request, 'upload_successful.html', context=context)

    def get(self,request):
        # 从数据库中取出数据
        value = Text_uploadModel.objects.all()
        # 临时定义个字典
        context = {
            'get_data':value
        }
        return render(request, 'text_successful.html',context=context)

    # 文本信息指定删除
    def Delete_Mes(request):
        # 调用自己写的删除方法
        del_mes = DeleteMessageClass(request,"text")
        del_mes.delete_message()

        return redirect(settings.URL+"/text_successful")



# 图片上传
class Img_Upload(APIView):
    def post(self,request):
        img = request.FILES['img']

        # 调用自己写的方法，用于将前端上传的音频写入本地文件夹中
        wf = WriteFilesClass(obj=img, file_type="img")
        context = wf.write_files()

        # 获取当前时间
        now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

        # 获取到用户的ip地址
        from MyTool.GeTIp import MyIp
        my_ip = MyIp()
        ip = my_ip.get_ip()
        print(f"ip:{ip}")

        username = "小名"
        # 查询数据库
        get_value = Imgs_uploadModel.objects.filter(username=username,image_name=img.name)
        print("从数据库中查询数据\n", get_value)

        data_dict = {"username": username, "time": now_time,"image":None,"image_name":img.name, "ip": ip}
        print(f"data_dict:{data_dict}")
        if str(get_value) != "<QuerySet []>":
            print("查询出相关数据")
            get_value.delete()
        # 将用户上传的文本存入数据库中
        serializers = Image_UploadSerializers(data=data_dict)
        serializers.is_valid(raise_exception=True)
        serializers.save()

        return render(request,'upload_successful.html',context=context)

    def get(self,request):

        # # 调用自己写的方法，用于读取本地文件，将本地文件显示在前端页面
        # wf = WriteFilesClass(file_type="img")
        # context = wf.read_files()

        # 从数据库中读取图片名称
        # 从数据库中取出数据
        value = Imgs_uploadModel.objects.all()
        # 临时定义个字典
        context = {
            'get_data': value
        }


        return render(request,'imgs_successful.html',context=context)

    # 图片信息指定删除
    def Delete_Mes(request):
        # 调用自己写的删除方法
        del_mes = DeleteMessageClass(request, "img")
        del_mes.delete_message()

        return redirect(settings.URL + "/imgs_successful")



# 音频上传
class Music_Upload(APIView):

    def post(self,request):
        music = request.FILES['music']
        print(music)
        # 调用自己写的方法，用于将前端上传的音频写入本地文件夹中
        wf = WriteFilesClass(obj=music,file_type="music")
        context = wf.write_files()
        return render(request,'upload_successful.html',context=context)

    def get(self,request):
        # 调用自己写的方法，用于读取本地文件，将本地文件显示在前端页面
        wf = WriteFilesClass(file_type="music")
        context = wf.read_files()
        return render(request, 'music_successful.html', context=context)



# 视频上传
class Video_Upload(APIView):
    def post(self,request):
        video = request.FILES['video']
        print(video)
        # 调用自己写的方法，用于将前端上传的音频写入本地文件夹中
        wf = WriteFilesClass(obj=video, file_type="video")
        context = wf.write_files()
        return render(request, 'upload_successful.html', context=context)
    def get(self,request):
        # 调用自己写的方法，用于读取本地文件，将本地文件显示在前端页面
        wf = WriteFilesClass(file_type="video")
        context = wf.read_files()
        return render(request, 'video_successful.html', context=context)


# 个人中心
class PersonalCenter(APIView):
    def post(self,request):
        pass



# 关于我们
class About_me(APIView):
    def post(self,request):
        pass




